import dotenv from 'dotenv';
import path from 'path';
import { existsSync } from 'fs';

// 根据环境加载不同配置
const envFile = process.env.NODE_ENV === 'test' ? '.env.test' : '.env';
const envPath = path.resolve(process.cwd(), envFile);
if (!existsSync(envPath)) {
  throw new Error(`Missing ${envFile} at ${envPath}`);
}
const { parsed } = dotenv.config({ path: envFile });
if (!parsed) {
  throw new Error(`Failed to parse ${envFile}`);
}

// 配置校验
const requiredEnv = ['NODE_ENV', 'MONGODB_URI', 'JWT_SECRET'];
requiredEnv.forEach(name => {
  if (!process.env[name]) {
    throw new Error(`Environment variable ${name} is required`);
  }
});

export default {
  app: {
    env: process.env.NODE_ENV || 'development',
    port: parseInt(process.env.PORT, 10) || 3000
  },
  
  debug: {
    queryLog: process.env.DB_QUERY_LOG === 'true',
    slowQueryThreshold: parseInt(process.env.SLOW_QUERY_MS, 10) || 1000
  },
  
  db: {
    uri: process.env.MONGODB_URI + '?retryWrites=true&w=majority',
    options: {
      maxPoolSize: parseInt(process.env.MONGODB_POOL_SIZE, 10) || 50,
      minPoolSize: 5,
      serverSelectionTimeoutMS: 5000,
      heartbeatFrequencyMS: 30000,
      ssl: process.env.NODE_ENV === 'production'
    }
  },
  
  jwt: {
    secret: process.env.JWT_SECRET,
    expiresIn: process.env.TOKEN_EXPIRES_IN || '7d',
    audience: process.env.JWT_AUDIENCE || 'webapp',
    issuer: process.env.JWT_ISSUER || 'api-server'
  },
  
  upload: {
    dir: process.env.UPLOAD_DIR || './uploads',
    maxFileSize: parseInt(process.env.MAX_FILE_SIZE, 10) || 10 * 1024 * 1024,
    allowedTypes: process.env.ALLOWED_MIME_TYPES?.split(',') || ['image/jpeg', 'image/png']
  },

  debug: {
    queryLog: process.env.DB_QUERY_LOG === 'true',
    slowQueryThreshold: parseInt(process.env.SLOW_QUERY_MS, 10) || 1000
  }
};